<!DOCTYPE html>
<html>
<head>
  <style>
      /* 定义画布 */
      #line-background {
          position: absolute;
          top: 0;
          left: 0;
          width: 100%;
          height: 100%;
          background-color: #111; /* 背景颜色 */
      }
  </style>
</head>
<body>
<!-- 画布容器 -->
<div id="line-background"></div>

<script>
  // 获取画布容器
  const canvasContainer = document.getElementById('line-background');

  // 创建画布
  const canvas = document.createElement('canvas');
  canvas.width = window.innerWidth;
  canvas.height = window.innerHeight;
  canvasContainer.appendChild(canvas);

  // 获取绘图上下文
  const ctx = canvas.getContext('2d');

  // 定义随机整数生成函数
  function randomInt(min, max) {
    return Math.floor(Math.random() * (max - min + 1)) + min;
  }

  // 定义随机颜色生成函数
  function randomColor() {
    const r = randomInt(0, 255);
    const g = randomInt(0, 255);
    const b = randomInt(0, 255);
    return `rgb(${r}, ${g}, ${b})`;
  }

  // 定义线条类
  class Line {
    constructor() {
      this.x1 = randomInt(0, canvas.width);
      this.y1 = randomInt(0, canvas.height);
      this.x2 = randomInt(0, canvas.width);
      this.y2 = randomInt(0, canvas.height);
      this.color = randomColor();
      this.speedX1 = (Math.random() - 0.5) * 2; // X1轴速度在 -1 到 1 之间
      this.speedY1 = (Math.random() - 0.5) * 2; // Y1轴速度在 -1 到 1 之间
      this.speedX2 = (Math.random() - 0.5) * 2; // X2轴速度在 -1 到 1 之间
      this.speedY2 = (Math.random() - 0.5) * 2; // Y2轴速度在 -1 到 1 之间
    }

    // 绘制线条
    draw() {
      ctx.beginPath();
      ctx.moveTo(this.x1, this.y1);
      ctx.lineTo(this.x2, this.y2);
      ctx.strokeStyle = this.color;
      ctx.lineWidth = 2;
      ctx.stroke();
    }

    // 更新线条位置
    update() {
      this.x1 += this.speedX1;
      this.y1 += this.speedY1;
      this.x2 += this.speedX2;
      this.y2 += this.speedY2;

      // 边界检测，碰到边界反弹
      if (this.x1 < 0 || this.x1 > canvas.width) {
        this.speedX1 = -this.speedX1;
      }
      if (this.y1 < 0 || this.y1 > canvas.height) {
        this.speedY1 = -this.speedY1;
      }
      if (this.x2 < 0 || this.x2 > canvas.width) {
        this.speedX2 = -this.speedX2;
      }
      if (this.y2 < 0 || this.y2 > canvas.height) {
        this.speedY2 = -this.speedY2;
      }

      this.draw();
    }
  }

  // 创建线条群
  const lines = [];
  const numLines = 50;
  for (let i = 0; i < numLines; i++) {
    lines.push(new Line());
  }

  // 动画循环
  function animate() {
    requestAnimationFrame(animate);
    ctx.clearRect(0, 0, canvas.width, canvas.height);

    for (let i = 0; i < lines.length; i++) {
      lines[i].update();
    }
  }

  animate();
</script>
</body>
</html>
